﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Globalization;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Drawing.Imaging;
using Buffalo.Lib.Common;
using System.Web.Mvc;
using Buffalo.Administration.DAL;
using Buffalo.Administration.Enum;

/// <summary>
/// Summary description for CommonManager
/// </summary>
namespace Buffalo.Web.Areas.Tourism
{
    public class CommonManager
    {
        const int IMAGE_DEFAULT_HEIGHT = 300;
        public CommonManager()
        {
        }

        public static bool IsMatchString(string source, string regString)
        {
            Regex reg = new Regex(regString, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            return reg.IsMatch(source);
        }

        //Check If A String Value Is Numeric
        public static bool IsNumeric(string strToCheck)
        {
            return Regex.IsMatch(strToCheck, "^\\d+(\\.\\d+)?$");
        }

        public static DateTime GetFirstDateOfMonth(DateTime date)
        {
            return Convert.ToDateTime(string.Format("{0}-{1}-{2}", date.Month, 1, date.Year));
        }
        public static DateTime GetFirstDateOfCurrentMonth()
        {
            return Convert.ToDateTime(string.Format("{0}-{1}-{2}", System.DateTime.Now.Month, 1, System.DateTime.Now.Year));
        }
        public static DateTime GetEndDateOfMonth(DateTime date)
        {
            int month = date.Month;
            int year = date.Year;
            int day = System.DateTime.DaysInMonth(year, month);
            return Convert.ToDateTime(string.Format("{0}-{1}-{2}", month, day, year));
        }
        public static DateTime GetEndDateOfCurrentMonth()
        {
            int month = System.DateTime.Now.Month;
            int year = System.DateTime.Now.Year;
            int day = System.DateTime.DaysInMonth(year, month);
            return Convert.ToDateTime(string.Format("{0}-{1}-{2}", month, day, year));
        }
        public static bool CheckEmail(string email)
        {

            string pattern = @"^[-a-zA-Z0-9][-.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[-.a-zA-Z0-9]+)*\.
                    (com|edu|info|gov|int|mil|vn|net|org|biz|name|museum|coop|aero|pro|tv|[a-zA-Z]{2})$";
            //Regular expression object
            Regex check = new Regex(pattern, RegexOptions.IgnorePatternWhitespace);
            //boolean variable to return to calling method
            bool valid = false;

            //make sure an email address was provided
            if (string.IsNullOrEmpty(email))
            {
                valid = false;
            }
            else
            {
                //use IsMatch to validate the address
                valid = check.IsMatch(email);
            }
            //return the value to the calling method
            return valid;
        }
        public static bool CheckPhoneNumber(string phoneNumber)
        {
            String PhoneNumber = "0123456789.()-, ";
            for (int Idx = 0; Idx < phoneNumber.Length; Idx++)
            {
                String Char = phoneNumber.Substring(Idx, 1);
                bool Match = false;
                for (int Idx1 = 0; Idx1 < PhoneNumber.Length; Idx1++)
                {
                    if (Char == PhoneNumber.Substring(Idx1, 1))
                        Match = true;
                }
                if (!Match)
                    return false;
            }
            return true;
        }
        public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
        {
            DataTable dtReturn = new DataTable();

            // column names 
            PropertyInfo[] oProps = null;

            if (varlist == null) return dtReturn;

            foreach (T rec in varlist)
            {
                // Use reflection to get property names, to create table, Only first time, others  will follow 
                if (oProps == null)
                {
                    oProps = ((Type)rec.GetType()).GetProperties();
                    foreach (PropertyInfo pi in oProps)
                    {
                        Type colType = pi.PropertyType;

                        if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                        {
                            colType = colType.GetGenericArguments()[0];
                        }

                        dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                    }
                }

                DataRow dr = dtReturn.NewRow();

                foreach (PropertyInfo pi in oProps)
                {
                    dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
                    (rec, null);
                }

                dtReturn.Rows.Add(dr);
            }
            return dtReturn;
        }
        public static int? ParseInt(string value)
        {
            if (value == "" || value == string.Empty) return null;
            return Convert.ToInt32(value);
        }

        public static double? ParseDouble(string value)
        {
            if (value == "" || value == string.Empty) return null;
            return Convert.ToDouble(value);
        }

        public static decimal? ParseDecimal(string value)
        {
            if (value == "" || value == string.Empty) return null;
            return Convert.ToDecimal(value);
        }


        public static string ParseString(string value)
        {
            if (value == "" || value == string.Empty) return null;
            return value;
        }

        public static bool ValidDateValue(string Day, string Month, string Year)
        {
            if (Day == "") Day = string.Empty;
            if (Month == "") Month = string.Empty;
            if (Year == "") Year = string.Empty;

            if (Day != string.Empty && Month == string.Empty && Year == string.Empty) return false;
            if (Day != string.Empty && Month != string.Empty && Year == string.Empty) return false;
            if (Day != string.Empty && Month == string.Empty && Year != string.Empty) return false;
            if (Day == string.Empty && Month != string.Empty && Year == string.Empty) return false;

            return true;
        }

        public static string ParseDateToString(DateTime dateTime, bool IsTypeVN)
        {
            if (dateTime == null) return string.Empty;
            string value = string.Empty;
            string day = dateTime.Day < 10 ? "0" + dateTime.Day.ToString() : dateTime.Day.ToString();
            string month = dateTime.Month < 10 ? "0" + dateTime.Month.ToString() : dateTime.Month.ToString();
            if (IsTypeVN)
            {
                value = day + "/" + month + "/" + dateTime.Year;
            }
            else value = month + "/" + day + "/" + dateTime.Year;

            return value;
        }
        public static string GetCurrentCulture()
        {
            string cultureName = ConfigurationManager.AppSettings["CultureName"];
            return cultureName == null ? "vi-VN" : cultureName;
        }
        public static string GetPhysicalAppPath()
        {
            return HttpContext.Current.Request.MapPath("/");
        }
        public static string GetAppPath()
        {
            return "~";
            //string sAbsUri = HttpContext.Current.Request.Url.AbsoluteUri;
            //string sRawUrl = HttpContext.Current.Request.RawUrl;
            //string path = string.Empty;
            //if (HttpContext.Current.Request.ApplicationPath == "/")
            //    path = sAbsUri.Substring(0, sAbsUri.Length - sRawUrl.Length);
            //else
            //    path = sAbsUri.Substring(0, sAbsUri.Length - sRawUrl.Length) + HttpContext.Current.Request.ApplicationPath;
            //return path;
        }
        #region GetDataItem
        public static T GetDataItem<T>(object dataItem, string fieldName, object defaultValue)
        {
            object value = DataBinder.Eval(dataItem, fieldName);
            if (value == null || value.Equals(DBNull.Value))
                if (defaultValue != null && !defaultValue.Equals(DBNull.Value))
                    return (T)defaultValue;
                else
                    return default(T);
            else
                return (T)value;
        }
        public static T GetDataItem<T>(object dataItem, string fieldName)
        {
            object value = DataBinder.Eval(dataItem, fieldName);
            if (value == null || value.Equals(DBNull.Value))
                return default(T);
            else
                return (T)value;
        }
        public static object GetDataItemDate(object dataItem, string fieldName)
        {
            object dateValue = DataBinder.Eval(dataItem, fieldName);
            if (dateValue == null || dateValue.Equals(DBNull.Value) || dateValue.Equals(Util.NullDateTime) || dateValue.Equals(DateTime.MinValue))
                return null;
            else
                return Convert.ToDateTime(dateValue);
        }
        #endregion GetDataItem
        #region public methods
        public static void Alert(Page page, string message)
        {
            string strWindowTitle = string.Empty;// "Delete ";
            string strWidth = "330";
            string strHeight = "200";

            string alert = "<script language='javascript'>" + "alert('" + message + "', " + strWidth + ", " + strHeight + ", '" + strWindowTitle + "');" + "</script>";

            page.ClientScript.RegisterClientScriptBlock(page.GetType(), "Alert", alert);
        }
        #endregion public methods
        public static void ShowStatusMessage(Page page, string statusMessage)
        {
            UserControl footer = (UserControl)page.Master.FindControl("footer");
            if (footer != null)
            {
                Label lblStatus = (Label)footer.FindControl("lblStatus");
                if (lblStatus != null)
                {
                    lblStatus.Text = statusMessage;
                }
            }

        }
        public static string GetAppSetting(string key)
        {
            try
            {
                return ConfigurationManager.AppSettings[key];
            }
            catch (Exception)
            {

                throw;
            }
        }

        public static void SetCurrentCulture()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(CommonManager.GetCurrentCulture());
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(CommonManager.GetCurrentCulture());
        }

        public static string ReadLayoutFile(string fileName)
        {
            StreamReader streamReader = new StreamReader(fileName);
            return streamReader.ReadToEnd();
        }

        public static string GetCurrentUrl()
        {
            Uri url = HttpContext.Current.Request.Url;
            return url.Scheme + "://" + url.Host + ":" + url.Port;
        }
        public static string FormatDouble(double? doubleValue)
        {
            return FormatDouble(doubleValue, 0);
        }
        public static string FormatPoint(double? doubleValue)
        {
            return string.Format("{0:0.#}", doubleValue);
        }
        public static string FormatDouble(object doubleValue)
        {
            return FormatDouble(Util.ToSafeDouble(doubleValue), 0);
        }
        public static string FormatDouble(double? doubleValue, int decimalNum)
        {
            double dblValue = doubleValue == null ? 0 : (double)doubleValue;
            string decimalFormat = string.Empty;
            for (int i = 1; i <= decimalNum; i++)
            {
                decimalFormat += "0";
            }
            string formatString = string.Empty;
            if (decimalNum > 0)
                formatString = "{0:#,#." + decimalFormat + "}";
            else
                formatString = "{0:#,#}";
            return string.Format(formatString, dblValue);
        }

        public static bool SendMail(List<string> toMails, string emailSubject, string emailBody, string[] attachments)
        {
            return SendMail(toMails, null, null, emailSubject, emailBody, attachments);
        }
        public static bool SendMail(List<string> toMails, List<string> ccMails, List<string> bccMails, string emailSubject, string emailBody, string[] attachments)
        {
            SmtpConfiguration smtpConfiguration = GetSmtpConfiguration();
            return SmtpMail.SendMail(
                smtpConfiguration.UserName,
                toMails, ccMails, bccMails, null, System.Net.Mail.MailPriority.High,
                emailSubject,
                emailBody,
                MailFormat.Html, Encoding.UTF8,
                attachments,
                smtpConfiguration.SMTPServer,
                smtpConfiguration.SMTPPort,
                SmtpAuthentication.Basic,
                smtpConfiguration.UserName,
                smtpConfiguration.Password,
                smtpConfiguration.UseSSL);
        }
        private static SmtpConfiguration GetSmtpConfiguration()
        {
            SmtpConfiguration smtpConfiguration = new SmtpConfiguration();
            smtpConfiguration.SMTPServer = ConfigurationManager.AppSettings["DefaultSMTPServer"];
            smtpConfiguration.SMTPPort = int.Parse(ConfigurationManager.AppSettings["DefaultSMTPPort"]);
            smtpConfiguration.UserName = ConfigurationManager.AppSettings["SMTPUser"];
            smtpConfiguration.Password = ConfigurationManager.AppSettings["SMTPPassword"];
            smtpConfiguration.UseSSL = bool.Parse(ConfigurationManager.AppSettings["SMTPUseSsl"]);

            return smtpConfiguration;
        }
        public static bool OpenXlsFile(string xlsFileName)
        {
            return OpenFile(xlsFileName, "application/xls");
        }
        public static bool OpenPdfFile(string pdfFileName)
        {
            return OpenFile(pdfFileName, "application/pdf");

        }
        private static bool OpenFile(string fileName, string mimeType)
        {
            try
            {
                FileInfo file = new FileInfo(fileName);
                // Clear the content of the response
                HttpContext.Current.Response.ClearContent();

                //// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);

                //// Add the file size into the response header
                HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());

                // Set the ContentType
                HttpContext.Current.Response.ContentType = mimeType;

                // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
                HttpContext.Current.Response.TransmitFile(file.FullName);
                //HttpContext.Current.Response.WriteFile(file.FullName);

                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.Close();


                // End the response
                //HttpContext.Current.Response.End();
                return true;
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        public static void LogException(Exception exception)
        {
            var exceptionLogger = new ExceptionLogger(exception);
            exceptionLogger.LogToEventLog();
        }
        public static void SafeAssignComboValue(DropDownList combo, string value)
        {
            value = string.IsNullOrEmpty(value) ? string.Empty : value;
            ListItem item = combo.Items.FindByValue(value);
            if (item != null)
                combo.SelectedValue = item.Value;
        }

        public static void PackSystem()
        {
            try
            {
                //delete temp folder
                string folder = string.Format(@"{0}\Buffalo\Buffalo.UI.School\Temp", HttpContext.Current.Server.MapPath(@".\"));
                Util.DeleteOldFiles (folder , "*.*", DateTime.Now.AddDays (-3));
            }
            catch (Exception)
            {
                
                throw;
            }
        }
        public static string GetModuleFolder()
        {
            return string.Format(@"{0}\Areas\Tourism", HttpContext.Current.Server.MapPath(@"~"));
        }
    }
}